<template>
	<!-- #ifdef H5 -->
	<fui-sticky>
		<fui-nav-bar title="设置" @leftClick="navigateBack">
			<fui-icon name="arrowleft"></fui-icon>
		</fui-nav-bar>
	</fui-sticky>
	<!-- #endif -->
	<view style="padding: 20rpx;background-color: #fff;">
		<fui-list>
			<fui-list-cell :highlight="false" @click="eventClick('头像')">
				<text>头像</text>
				<fui-avatar size="small" :src="userInfo?.avatar"></fui-avatar>
			</fui-list-cell>
			<fui-list-cell :highlight="false" @click="eventClick('昵称')">
				<text>昵称</text>
				<text class="fui-text__explain">{{userInfo?.nickname}}</text>
			</fui-list-cell>
			<fui-list-cell :highlight="false">
				<text>手机号</text>
				<text class="fui-text__explain">{{userInfo?.mobile}}</text>
			</fui-list-cell>
			<fui-list-cell :highlight="false" @click="eventClick('邀请人')">
				<text>设置邀请人</text>
				<text class="fui-text__explain">{{userInfo?.inviter_uid?.length>0?'已绑定':'去设置'}}</text>
			</fui-list-cell>
			<fui-list-cell :highlight="false">
				<text>推送信息</text>
				<fui-switch checked @change="eventClick('推送信息')"></fui-switch>
			</fui-list-cell>
			<fui-list-cell arrow :highlight="false" @click="eventClick('密码')">
				<text>修改密码</text>
			</fui-list-cell>
			<fui-list-cell :highlight="false" @click="eventClick('清理缓存')">
				<text>清理缓存</text>
			</fui-list-cell>
			<fui-list-cell arrow :highlight="false" @click="eventClick('注销账户')">
				<text>注销账户</text>
			</fui-list-cell>
			<fui-list-cell arrow :highlight="false" @click="eventClick('隐私协议')">
				<text>隐私协议</text>
			</fui-list-cell>
			<fui-list-cell arrow marginTop='20' :highlight="false" @click="eventClick('关于我们')">
				<text>关于我们</text>
			</fui-list-cell>
		</fui-list>
		<fui-button text="退出登录" :margin="['50rpx','0','0','0']" @click="eventClick('退出登录')"></fui-button>

		<fui-modal :show="form.logOut" maskClosable title="系统提示" @cancel="closePopup" descr="确定退出吗？" @click="onlogOut"></fui-modal>


		<!-- 修改昵称 -->
		<fui-bottom-popup :show="form.ncshow" @close="closePopup" safeArea>
			<view class="fui-custom__wrap">
				<fui-form ref="formRef">
					<fui-section color="#fd5531" title="修改昵称" isLine></fui-section>
					<fui-input maxlength="8" autofocus v-model="form.nickname" :cursorSpacing="form.cursorSpacing" @focus="keyboardheightchange" placeholder="请输入昵称"></fui-input>
					<fui-button text="确认修改" @click="eventClick('修改昵称')"></fui-button>
				</fui-form>
			</view>
		</fui-bottom-popup>
		<!-- 修改邀请码 -->
		<fui-bottom-popup :show="form.showinviter" @close="closePopup" safeArea>
			<view class="fui-custom__wrap">
				<fui-form ref="formRef">
					<fui-section color="#fd5531" title="设置邀请人" isLine></fui-section>
					<fui-input autofocus v-model="formData.inviteCode" :cursorSpacing="form.cursorSpacing" @focus="keyboardheightchange" placeholder="输入正确的邀请码"></fui-input>
					<fui-button text="确认修改" @click="eventClick('设置邀请人')" :loading="formItem.loading"></fui-button>
				</fui-form>
			</view>
		</fui-bottom-popup>
		<!-- 修改密码 -->
		<fui-bottom-popup :show="form.showPassword" @close="closePopup" safeArea>
			<view class="fui-custom__wrap">
				<fui-form ref="formRefs">
					<fui-section color="#fd5531" :marginBottom="30" title="修改密码" isLine></fui-section>
					<fui-input autofocus v-model="formDatas.oldPassword" :cursorSpacing="form.cursorSpacing" @focus="keyboardheightchange" placeholder="输入旧密码"></fui-input>
					<fui-input autofocus v-model="formDatas.newPassword" :cursorSpacing="form.cursorSpacing" @focus="keyboardheightchange" placeholder="输入新密码"></fui-input>
					<fui-button text="确认修改" @click="eventClick('修改密码')" :loading="formItems.loading"></fui-button>
				</fui-form>
			</view>
		</fui-bottom-popup>
	</view>
</template>
<script setup>
	import { LoginStore } from '@/store/modules/login.js'
	import { useAcceptInvite } from "@/hooks/useAcceptInvite.js"
	import { useUploadFile } from '@/hooks/useUploadFile.js'
	import { useUpdatePwd } from '@/hooks/useUpdatePwd.js'
	import { ref, reactive, computed } from 'vue'
	import { onLoad } from "@dcloudio/uni-app";
	import { checkPssword } from "@/utils/validator.js"
	const updateUserApi = uniCloud.importObject('qc-user', { customUI: true })
	const { uploadFile } = useUploadFile()
	// 校验规则(设置邀请码)
	const rules = reactive(
		[{
			name: "inviteCode",
			rule: ["required", "isEnOrNo"],
			msg: ["请输入正确的邀请码", '邀请码只可以输入数字或字母']
		}]
	)
	// 校验规则(修改密码)
	const rules2 = reactive(
		[{
				name: "oldPassword",
				rule: ["required"],
				msg: ["输入内容不能为空"]
			},
			{
				name: "newPassword",
				rule: ["required"],
				msg: ["请设置登录密码", "密码必须包含字母，密码长度必须在6-16位之间"],
				validator: [{ msg: '密码必须包含字母，密码长度必须在6-16位之间', method: checkPssword }]
			}
		]
	)
	const formRef = ref(null) // 获取表单实例
	const formRefs = ref(null) // 获取表单实例
	// 修改邀请人
	const { formData, formItem, submit } = useAcceptInvite(formRef, rules)
	// 修改密码
	const { formDatas, formItems, updatePwd } = useUpdatePwd(formRefs, rules2)
	// 获取用户信息
	const userInfo = computed(() => (LoginStore().userInfo))

	// 数据
	let form = reactive({
		nickname: null, //用户昵称
		ncshow: false, //昵称弹窗状态
		showinviter: false, //邀请码弹窗状态
		logOut: false, //退出登录弹窗
		cursorSpacing: 100, //键盘高度
		showPassword: false //修改密码状态
	})

	// 公共事件
	const eventClick = async (code) => {
		switch (code) {
			case '头像':
				updateAvatar()
				break;
			case '昵称':
				form.ncshow = true
				break;
			case '邀请人':
				if (userInfo?.value?.inviter_uid == undefined || userInfo?.value?.inviter_uid?.length == 0) {
					form.showinviter = true
				}
				break;
			case '推送信息':
				break;
			case '密码':
				form.showPassword = true
				break;
			case '关于我们':
				uni.fui.href('/pages/user/setup/about')
				break;
			case '隐私协议':
				uni.fui.href('/pages/user/setup/privacy')
				break;
			case '修改昵称':
				updateName()
				break;
			case '设置邀请人':
				const data = await submit()
				if (data.errCode == 0) form.showinviter = false
				break;
			case '修改密码':
				const res = await updatePwd()
				if (res.errCode == 0) form.showPassword = false
				break;
			case '清理缓存':
				clearTmp()
				break;
			case '注销账户':
				uni.fui.href('/pages/user/deactivate/deactivate')
				break;
			case '退出登录':
				form.logOut = true
				break;
			default:
				break;
		}
	}

	// 获取键盘高度
	const keyboardheightchange = ({ detail }) => {
		form.cursorSpacing = detail.height
	}


	// 退出登录
	const onlogOut = (e) => {
		closePopup()
		if (e.index == 1) LoginStore().logout()
	}
	// 关闭抽屉
	const closePopup = () => {
		form.showPassword = false
		form.ncshow = false
		form.showinviter = false
		form.logOut = false
	}
	// 返回上一层
	// #ifdef H5 
	const navigateBack = () => {
		uni.navigateBack()
	}
	// #endif

	// 更新昵称
	const updateName = async () => {
		if (form.nickname == null) {
			return uni.fui.toast("输入不可为空")
		}
		try {
			const res = await updateUserApi.updateUserInfo({ nickname: form.nickname, user_id: userInfo.value._id })
			uni.fui.toast(res.errMsg)
			closePopup()
			LoginStore().updateUserInfo()
		} catch (e) {
			uni.fui.toast(e.errMsg)
		}
	}
	//更换头像
	const updateAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			success: async (res) => {
				if (res.errMsg == 'chooseImage:ok') uni.fui.toast('更换成功')
				userInfo.value.avatar = res.tempFilePaths[0]
				const file = await uploadFile(res.tempFiles, 'avatar', 'url')
				await updateUserApi.updateUserInfo({ avatar: file[0].fileID, user_id: userInfo?.value?._id })
				LoginStore().updateUserInfo()
			}
		});
	}
	// 清除本地缓存
	const clearTmp = () => {
		uni.showLoading({
			title: '清除中',
			mask: true
		});
		/*
		任何临时存储或删除不直接影响程序运行逻辑（清除缓存必定造成业务逻辑的变化，如：打开页面的图片不从缓存中读取而从网络请求）的内容都可以视为缓存。主要有storage、和file写入。
		缓存分为三部分		
			原生层（如：webview、x5播放器的、第三方sdk的、地图组件等）
			前端框架（重启就会自动清除）
			开发者自己的逻辑（如：
				本示例的 检测更新功能下载了apk安装包，
				其他逻辑需要根据开发者自己的业务设计
				比如：有聊天功能的应用，聊天记录是否视为缓存，还是单独提供清除聊天记录的功能由开发者自己设计
			）
		*/
		uni.getSavedFileList({
			success: res => {
				if (res.fileList.length > 0) {
					uni.removeSavedFile({
						filePath: res.fileList[0].filePath,
						complete: res => {
							uni.hideLoading()
							uni.showToast({
								title: '清除成功',
								icon: 'none'
							});
						}
					});
				} else {
					uni.hideLoading()
					uni.showToast({
						title: "清除成功",
						icon: 'none'
					});
				}
			},
			fail(err) {
				uni.showToast({
					title: "清除成功",
					icon: 'none'
				});
			}
		});
	}
</script>

<style lang="scss" scoped>
	.fui-custom__wrap {
		padding: 32rpx;
		height: 360rpx;

		.fui-form__wrap {
			height: 100% !important;
			display: flex;
			flex-direction: column;

			.fui-button__wrap {
				flex: 0 !important;
			}
		}
	}
</style>